package top.lvkun.basic.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;

public class JsonUtils {

    /**
     * 对象转换成json字符串
     * @param object
     * @return
     */
    public static String toJsonStr(Object object){
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            return objectMapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 将json字符串转换成指定的对象
     * @param jsonStr
     * @param clazz
     * @param <T>
     * @return
     */
    public static<T> T toObj(String jsonStr,Class<T> clazz){
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            return objectMapper.readValue(jsonStr,clazz);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;

    }
}
